package com.qingxin.park.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qingxin.park.entity.Company;
import com.qingxin.sys.dao.Querier;
import com.qingxin.sys.dao.Updater;
import com.qingxin.sys.entity.LoginUser;
import com.qingxin.sys.entity.SysGroup;
import com.qingxin.sys.mvc.PageParam;
import com.qingxin.sys.mvc.Pager;
import com.qingxin.sys.mvc.SysError;
import com.qingxin.sys.service.BaseService;
import com.qingxin.sys.service.SysGroupService;
import com.qingxin.sys.support.SystemCfg;
import com.qingxin.sys.support.UploadFile;
import com.qingxin.sys.utils.BeanUtil;
import com.qingxin.sys.utils.StringUtils;
import com.qingxin.ui.bean.TreeNode;
/**
 * 企业
 * @author Administrator
 *
 */
@Service
public class CompanyService extends BaseService<Company, String> {

	@Autowired
	private SysGroupService sysGroupService;
	
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getAllCompanyData(){
		List<TreeNode> list = new ArrayList<>();
		
		StringBuilder hql = new StringBuilder();
		hql.append("from Company c order by c.companyName asc");
		List<Company> companies = listByHql(hql.toString());
		if(companies != null){
			for(Company company : companies){
				list.add(new TreeNode(company.getCompanyid(), company.getCompanyName(), false));
			}
		}
		return list;
	}
	
	
	public List<TreeNode> getCompanyData(LoginUser loginUser){
		return getCompanyData(null, loginUser);
	}
	
	
	@SuppressWarnings("unchecked")
	public List<TreeNode> getCompanyData(String groupid, LoginUser loginUser){
		List<TreeNode> list = new ArrayList<>();
		
		StringBuilder hql = new StringBuilder();
		hql.append("from Company c ");
		
		if(StringUtils.isNotEmpty(groupid)){
			hql.append(" where c.groupid like '"+groupid.replace("'", "")+"%'");
		}else {
			if(!SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
				String uroupid = loginUser.getGroupid();
				SysGroup group = sysGroupService.get(uroupid);
				if(group.getGrouptype() == 3){
					uroupid = group.getPid();
				}
				hql.append(" where c.groupid like '"+uroupid+"%'");
			}
		}
		
		if(!SystemCfg.isDataAdminUser(loginUser)){
			hql.append(" and c.companyid in (select distinct v.company.companyid from SysUserCompRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}
		
		hql.append(" order by c.companyName asc");
		List<Company> companies = listByHql(hql.toString());
		if(companies != null){
			for(Company company : companies){
				list.add(new TreeNode(company.getCompanyid(), company.getCompanyName(), false));
			}
		}
		return list;
	}
	
	
	/**
	 * 获取企业列表，用于首页展示
	 * @param nums
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Company> listCompanies(int nums){
		Querier querier = Querier.create("select new com.qingxin.park.entity.Company(" +
				"companyid, companyNo, companyName, imgurl, remark)" +
				" from Company c order by c.createTime desc");
		querier.setMaxResults(nums);
		return listByQuerier(querier);
	}
	
	
	public Pager listPageCompanies(PageParam pageParam){
		Querier querier = Querier.create("select new com.qingxin.park.entity.Company(" +
				"companyid, companyNo, companyName, imgurl, remark)" +
				" from Company c order by c.createTime desc");
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	/**
	 * 列表数据
	 * @param materialid
	 * @param typeid
	 * @param materialName
	 * @param pageParam
	 * @param loginUser
	 * @return
	 */
	
	public Pager list(String groupid, String search, String companytype, String companyid, PageParam pageParam, LoginUser loginUser){
		Querier querier = Querier.create("select new com.qingxin.park.entity.Company(" +
				"c.companyid, c.companyType, c.companyName, c.companyNo, c.businessNo," +
				" c.corporatePerson, c.contactPerson, c.phone, c.address, c.companyLevel," +
				" c.postcodes, c.productDesc, c.productivity, c.mainbody, c.farmLevel, c.ccc, c.nameplate, c.isBuild,c.qrcode)" +
				" from Company c where 1=1 ");
		
		if(StringUtils.isEmpty(groupid) && !SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		
		/*if("2".equals(loginUser.getUser_type())){
			querier.append(" and c.farmPark.parkid in (select distinct v.farmPark.parkid from SysUserParkRel v where v.sysUser.userid='"+loginUser.getUserid()+"')");
		}*/
		if(StringUtils.isNotEmpty(groupid)){
			groupid = groupid.replace("'", "");
			querier.append(" and c.groupid like :groupid ");
			querier.setParam("groupid", groupid+"%");
		}
		if(StringUtils.isNotEmpty(search)){
			search = "%"+search.replace("'", "")+"%";
			querier.append(" and (companyName like :companyName)");
			querier.setParam("companyName", search);
		}
		querier.append(pageParam.getOrderby(" order by c.createTime desc", "c"));
		Pager pager = pageByQuerier(querier, pageParam);
		return pager;
	}
	
	
	/**
	 * 企业列表
	 * @param search
	 * @param pageParam
	 * @param loginUser
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Company> listForApp(String search, PageParam pageParam, LoginUser loginUser){
		Querier querier = Querier.create("from Company c where 1=1 ");
		
		String groupid = loginUser.getGroupid();
		if(StringUtils.isNotEmpty(groupid)){
			groupid = groupid.replace("'", "");
			querier.append(" and c.groupid like :groupid ");
			querier.setParam("groupid", groupid+"%");
		}
		
		if(StringUtils.isNotEmpty(search)){
			search = "%"+search.replace("'", "")+"%";
			querier.append(" and (c.companyName like :companyName)");
			querier.setParam("companyName", "%"+search+"%");
		}
		querier.append(pageParam.getOrderby(" order by c.createTime desc", "c"));
		
		List<Company> list = listByQuerier(querier, pageParam);
		return list;
	}
	
	
	/**
	 * 导出企业列表
	 * @param groupid
	 * @param loginUser
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public List<Company> listCompanies(String groupid, LoginUser loginUser){
		Querier querier = Querier.create("select new com.qingxin.park.entity.Company(" +
				"c.companyid, c.companyType, c.companyName, c.companyNo, c.businessNo," +
				" c.corporatePerson, c.contactPerson, c.phone, c.address, c.companyLevel," +
				" c.postcodes, c.productDesc, c.productivity, c.mainbody, c.farmLevel, c.ccc, c.nameplate, c.isBuild,c.qrcode)" +
				" from Company c where 1=1 ");
		
		if(StringUtils.isEmpty(groupid) && !SystemCfg.isAdminUser(loginUser) && !SystemCfg.isSystemAdminUser(loginUser)){
			groupid = loginUser.getGroupid();
		}
		if(StringUtils.isNotEmpty(groupid)){
			groupid = groupid.replace("'", "");
			querier.append(" and c.groupid like :groupid ");
			querier.setParam("groupid", groupid+"%");
		}
		querier.append(" order by c.createTime desc");
		return listByQuerier(querier);
	}
	
	
	
	/**
	 * 添加企业信息
	 * @param material
	 * @param typeid
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError add(Company company, LoginUser loginUser, HttpServletRequest request){
		//System.out.println(company.getCompanyid());
		
		if(StringUtils.isNotEmpty(company.getImgurl())){
			UploadFile.moveTmpTo(company.getImgurl(), UploadFile.DIR_COMPANY_IMG);
		}
		
		company.setCreateTime(new Date());
		company.setUpdateTime(new Date());
		company.setCreateBy(loginUser.getLogin_name());
		company.setUpdateBy(loginUser.getLogin_name());
		
		this.save(company);
		
		return null;
	}
	
	
	/**
	 * 修改企业信息
	 * @param company
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError update(Company company, LoginUser loginUser, HttpServletRequest request){
		Company old = getSafeEntity(company.getCompanyid());
		//company.setQrcode(company.getGroupid() +  company.getCompanyNo());
		
		if(StringUtils.isNotEmpty(company.getImgurl()) && !company.getImgurl().equals(old.getImgurl())){
			UploadFile.moveTmpTo(company.getImgurl(), UploadFile.DIR_COMPANY_IMG);
		}
		
		String fields = "companyid,companyType,companyName,businessNo,corporatePerson,contactPerson,phone,address," +
				"companyLevel,lat,lng,postcodes,productDesc,productivity,mainbody,farmLevel,ccc,nameplate,isBuild,imgurl,remark";
		BeanUtil.setTargetFields(old, company, fields, true);
		
		old.setUpdateBy(loginUser.getLogin_name());
		old.setUpdateTime(new Date());
		
		Updater<Company> updater = new Updater<>(old, fields+",updateBy,updateTime");
		this.update(updater);
		return null;
		
	}
	
	
	/**
	 * 删除
	 * @param companyids
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public Object delete(String[] companyids, LoginUser loginUser, HttpServletRequest request){
		for(String companyid : companyids){
			Company company = get(companyid);
			if(company==null){
				continue;
			}
			this.delete(company);
		}
		
		return null;
	}
	
	/**
	 * 生成二维码
	 * @param companyid
	 * @param groupid
	 * @param qrCode
	 * @param loginUser
	 * @param request
	 * @return
	 */
	public SysError updateQrCode(Company company,String qrCode, LoginUser loginUser, HttpServletRequest request){
		Company old = this.getSafeEntity(company.getCompanyid());
		String fields = "qrcode";
		
		//生成二维码
		
		
		BeanUtil.setTargetFields(old, company, fields, true);
		Updater<Company> updater = new Updater<>(old, fields);
		this.update(updater);
		return null;
	}
	
	/**
	 * 判断指定名称是否被使用
	 * @param materialName
	 * @param materialid
	* @param typeid
	 * @return
	 */
	public boolean isNameDuplicate(String companyName, String companyid){
		if(StringUtils.isEmpty(companyid)){
			Object obj = getByHql("select companyid from Company where companyName=? ", companyName);
			return obj!=null;
		}else {
			Object obj = getByHql("select companyid from Company where companyid<>? and companyName=? ", companyid, companyName);
			return obj!=null;
		}
	}
	
	
	
	/**
	 * 判断指定CODE是否被使用
	 * @param materialCode
	 * @param materialid
	 * @param typeid
	 * @return
	 */
	public boolean isCodeDuplicate(String companyNo, String companyid){
		if(StringUtils.isEmpty(companyid)){
			Object obj = getByHql("select companyid from Company where companyNo=? ", companyNo);
			return obj!=null;
		}else {
			Object obj = getByHql("select companyid from Company where companyid<>? and companyNo=? ", companyid, companyNo);
			return obj!=null;
		}
	}
	
	public Company getProductsView(String companyid){
		Company company = (Company) getByHql("from Company where companyid=?", companyid);
		return company;
	}
	
	public String getCompanyNoMax(){
		String companyNo = (String) getByHql("select max(companyNo) from Company");
		return companyNo;
	}
	
	
	/**
	 * 二维码排重
	 * @param groupid
	 * @param qrCode
	 * @return
	 */
	public boolean isqrCodeDuplicate(String groupid, String qrCode){
		String qrcode = groupid + qrCode;
		Object obj = getByHql("select qrcode from Company where qrcode=? ", qrcode);
		return obj!=null;
	}
}
